class FloatingWindow {
  constructor(selector) {
    this.element = document.querySelector(selector);
    this.isDragging = false;
    this.dragStartX = 0;
    this.dragStartY = 0;
    this.windowStartX = 0;
    this.windowStartY = 0;

    this.resizeHandle = null;
    this.isResizing = false;
    this.resizeStartWidth = 0;
    this.resizeStartHeight = 0;

    this.addEventListeners();
  }

  addEventListeners() {
    // 拖动事件处理
    this.element.addEventListener("mousedown", (e) => {
      if (e.target === this.element && !this.isResizing) {
        this.isDragging = true;
        this.dragStartX = e.clientX;
        this.dragStartY = e.clientY;
        this.windowStartX = this.element.offsetLeft;
        this.windowStartY = this.element.offsetTop;
      }
    });

    document.addEventListener("mousemove", (e) => {
      if (this.isDragging) {
        const diffX = e.clientX - this.dragStartX;
        const diffY = e.clientY - this.dragStartY;
        this.element.style.left = this.windowStartX + diffX + "px";
        this.element.style.top = this.windowStartY + diffY + "px";
      }
    });

    document.addEventListener("mouseup", () => {
      this.isDragging = false;
    });

    // 改变大小事件处理
    this.createResizeHandle();
  }

  createResizeHandle() {
    this.resizeHandle = document.createElement("div");
    this.resizeHandle.classList.add("resize-handle");
    this.element.appendChild(this.resizeHandle);

    this.resizeHandle.addEventListener("mousedown", (e) => {
      this.isResizing = true;
      this.resizeStartWidth = this.element.offsetWidth;
      this.resizeStartHeight = this.element.offsetHeight;
    });

    document.addEventListener("mousemove", (e) => {
      if (this.isResizing) {
        const diffX = e.clientX - this.resizeHandle.offsetLeft;
        const diffY = e.clientY - this.resizeHandle.offsetTop;
        this.element.style.width = this.resizeStartWidth + diffX + "px";
        this.element.style.height = this.resizeStartHeight + diffY + "px";
      }
    });

    document.addEventListener("mouseup", () => {
      this.isResizing = false;
    });
  }
}

// 使用示例
const myWindow = new FloatingWindow("#my-floating-window");
